//
//  DRMainVC.m
//  DreamRecorder
//
//  Created by Liboom on 2024/2/27.
//

#import "DRMainVC.h"
#import <AVFoundation/AVFoundation.h>
#import "DRMainModel.h"
@interface DRMainVC ()<UITableViewDelegate,UITableViewDataSource,AVAudioRecorderDelegate,AVAudioPlayerDelegate,UIGestureRecognizerDelegate>{
    AVAudioRecorder *recorder;
        AVAudioPlayer *player;
        /** 录音计时器 */
        NSTimer *recordTimer;
        /** 播放计时器 */
        NSTimer *playTimer;
        /** 录音时间 */
        NSInteger recordSecond;
        /** 录音分钟时间 */
        NSInteger minuteRecord;
        /** 播放时间 */
        NSInteger playSecond;
        /** 播放分钟时间 */
        NSInteger minutePlay;
        /** caf文件路径 */
        NSURL *tmpUrl;

}
@property(nonatomic, strong) UITableView *myTab;
@property(nonatomic, strong) NSMutableArray *dataArr;
@property(nonatomic, strong) UIView *floatBtn;
@property(nonatomic, strong) NSString *fileName, * filePath;
@end

@implementation DRMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArr = [NSMutableArray new];
    [self createUI];
    [self getData];
}

-(void)createUI{
    [self.view addSubview:self.myTab];
    
    
    self.floatBtn = [UIView new];
    self.floatBtn.backgroundColor = ThemeColor;
    self.floatBtn.cornerRadius = 30;
    [self.view addSubview:self.floatBtn];
    self.floatBtn.mm_width(60).mm_height(60).mm_center().mm_bottom(KTabbarSafeBottomMargin+40);
    
    UIImageView * boyin = [[UIImageView alloc]initWithImage:ImageMake(@"播音")];
    [self.floatBtn addSubview:boyin];
    boyin.sd_layout.centerXEqualToView(self.floatBtn).centerYEqualToView(self.floatBtn).widthIs(30).heightIs(30);
    UILongPressGestureRecognizer * pre = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    [self.floatBtn addGestureRecognizer:pre];
}
-(void)longPress:(UILongPressGestureRecognizer *)sender {
    switch (sender.state) {
        case UIGestureRecognizerStateBegan: {
            [self recordingAction];
        }break;
        case UIGestureRecognizerStateChanged: {
            ///
        }break;
        case UIGestureRecognizerStateEnded: {
            [self stopAction];
        }break;
        default:break;
    }
}
/**
 开始录音
 */
- (void)recordingAction {
    
    NSLog(@"开始录音");
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

    //录音设置
    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
    //录音格式
    [recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采样率
    [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
    //通道数
    [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //线性采样位数
    [recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];

    NSError *error = nil;
    // 沙盒目录Documents地址
    NSString *recordUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSDate *date = [NSDate date];
    self.fileName = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld:%02ld.caf",date.year,date.month,date.day,date.hour,date.minute,date.seconds];
    // caf文件路径
    self.filePath =[recordUrl stringByAppendingPathComponent:self.fileName];
    tmpUrl = [NSURL URLWithString:self.filePath];
    recorder = [[AVAudioRecorder alloc]initWithURL:tmpUrl settings:recordSettings error:&error];
    
    if (recorder) {
        //启动或者恢复记录的录音文件
        if ([recorder prepareToRecord] == YES) {
            [recorder record];

            recordSecond = 0;
            minuteRecord = 0;
            if(!recordTimer){
                recordTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordSecondChange) userInfo:nil repeats:YES];
                [recordTimer fire];
            }
        }
    }else {
        NSLog(@"录音创建失败");
    }
}

/**
 录音计时
 */
- (void)recordSecondChange {
    recordSecond ++;
    if (recordSecond > 59) {
        
        minuteRecord ++;
        recordSecond = 0;
    }
    self.myTitle = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minuteRecord,(long)recordSecond];
}
/**
 停止录音
 */
- (void)stopAction {
    
    NSLog(@"停止录音");
    //停止录音
    [recorder stop];
    recorder = nil;
    [recordTimer invalidate];
    recordTimer = nil;
    
    self.myTitle = [NSString stringWithFormat:@"%.2ld:%.2ld",(long)minuteRecord,(long)recordSecond];
    
    DRMainModel* mo = [DRMainModel new];
    mo.bg_tableName = TABLENAME;
    mo.filePath = self.filePath;
    mo.fileName = self.fileName;
    [mo bg_save];
    [self.dataArr removeAllObjects];
    [self getData];
}

-(void)getData{
    NSArray * arr = [DRMainModel bg_findAll:TABLENAME];
    [self.dataArr addObjectsFromArray:arr];
    [DLTools NeedResetNoViewWithView:self.myTab andArr:self.dataArr point:CGPointMake(SCREEN_WIDTH/2.0, SCREEN_HEIGHT/2 -80)];
}
#pragma mark 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    if(indexPath.row < self.dataArr.count){
        DRMainModel * mo = self.dataArr[indexPath.row];
        cell.textLabel.text = mo.fileName;
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (UITableView *)myTab {
    if (!_myTab) {
        _myTab = [[UITableView alloc] initWithFrame:Frame(0, kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT    ) style:UITableViewStyleGrouped];
        _myTab.dataSource = self;
        _myTab.delegate = self;
        _myTab.backgroundColor = UnderLineColor;
//        __weak typeof(self)weakSelf = self;
//        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            weakSelf.page = 1;
//            [weakSelf.dataArr removeAllObjects];
//            [weakSelf getData];
//        }];
    }
    return _myTab;
}

@end
